package com.hantanger.weblog.util;

import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class HtmlUtil {
	
	public static Pattern emailPattern = Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");

	
	/**
	 * 修补html代码，使标签补全
	 * @param html
	 * @return
	 */
	public static String repairHtml(String html){
		if(html == null){
			return "";
		}
		Document doc = Jsoup.parse(html);
		//去除非pre标签上的class属性
		Elements elements = doc.getElementsByAttribute("class");
		for(Element element : elements){
			if(!element.nodeName().equalsIgnoreCase("pre")){
				element.removeAttr("class");
			}
		}
		return doc.body().html();
	}
	
	public static int getInt(HttpServletRequest request, String param, int defaultValue){
		String paramValue = request.getParameter(param);
		int result = defaultValue;
		if(StringUtils.isNotBlank(paramValue)){
			try{
				result = Integer.parseInt(paramValue);
			}catch(Exception e){}
		}
		return result;
	}
	
	public static long getLong(HttpServletRequest request, String param, long defaultValue){
		String paramValue = request.getParameter(param);
		long result = defaultValue;
		if(StringUtils.isNotBlank(paramValue)){
			try{
				result = Long.parseLong(paramValue);
			}catch(Exception e){}
		}
		return result;
	}
	
	public static String getString(HttpServletRequest request, String param, String defaultValue){
		String paramValue = request.getParameter(param);
		String result = defaultValue;
		if(StringUtils.isNotBlank(paramValue)){
			result = paramValue;
		}
		return result;
	}
	
	public static boolean getBool(HttpServletRequest request, String param, boolean defaultValue){
		String paramValue = request.getParameter(param);
		boolean result = defaultValue;
		if(StringUtils.isNotBlank(paramValue)){
			try{
				result = Boolean.parseBoolean(paramValue);
			}catch(Exception e){}
		}
		return result;
	}
	
	public static void main(String[] args){
		System.out.println(repairHtml("<table><div>sfdwerwer<div>sdfwr</table>"));
	}
}
